package com.itcoon.cloud.framework.security.filter;

import com.itcoon.cloud.framework.security.config.properties.JwtTokenProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * created in 2021/4/26
 */

public class SwaggerApiKeyAuthFilter extends OncePerRequestFilter {

	private static final String AUTH_BASIC_PREFIX = "Basic ";

	private JwtTokenProperties jwtTokenProperties;
	public SwaggerApiKeyAuthFilter(JwtTokenProperties jwtTokenProperties) {
		this.jwtTokenProperties = jwtTokenProperties;
	}

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String accessToken = request.getHeader(jwtTokenProperties.getHeaderName());
		if (!StringUtils.isEmpty(accessToken)) {
			if (!accessToken.startsWith(jwtTokenProperties.getTokenValPrefix()) && !accessToken.startsWith(AUTH_BASIC_PREFIX)) {
				accessToken = jwtTokenProperties.getTokenValPrefix() + accessToken;
				request = new SuccessRequestWrapper(request, accessToken);
			}
		}
		filterChain.doFilter(request, response);
	}


	public static class SuccessRequestWrapper extends HttpServletRequestWrapper {

		private static final String AUTH_HEADER_NAME = "Authorization";
		private final String replaceAuthToken;

		public SuccessRequestWrapper(HttpServletRequest request, String replaceAuthToken) {
			super(request);
			this.replaceAuthToken = replaceAuthToken;
		}

		@Override
		public String getHeader(String name) {
			if (AUTH_HEADER_NAME.equals(name)) {
				return replaceAuthToken;
			}
			return super.getHeader(name);
		}
	}
}
